package com.bigger.controller;

import com.bigger.constant.ErrorConstant;
import com.bigger.exception.BaseException;
import com.bigger.result.Result;
import com.bigger.utils.MinIOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RequestMapping("/admin/common")
@RestController
public class CommonController {
    //这里uploadFile涉及到文件上传（以后需要改用阿里云OS存储的话，请更改对应依赖并在nacos中进行配置修改）
    @Autowired
    private MinIOUtil minIOUtil;
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        String fileName = generateFileName(file);
        try {
            String filePath = minIOUtil.uploadFile(fileName, file.getContentType(), file.getInputStream());
            return Result.success(filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 生成对应所需要的minio储存文件文件名
     * @param file
     * @return
     */
    private String generateFileName(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (filename != null) {
            int i = filename.lastIndexOf(".");
            String lastName = filename.substring(i);
            String contentType = file.getContentType();
            if (contentType.startsWith("image")) {
                return UUID.randomUUID() + lastName;
            }else {
                throw new BaseException(ErrorConstant.FILE_ERROR);
            }
        } else {
            throw new BaseException("未知错误");
        }
    }
}
